// app.js
import { promisifyAll } from 'miniprogram-api-promise'

const { arrayToTree, arrayToMap } = require('./utils/util')

const wxp = wx.p = {}
promisifyAll(wx, wxp)
const { baseUrl, viewUrl } = require('./config/index')

const MsgType = {
    200: { msg: '获取数据成功！', type: 'success' },
    201: { msg: '获取数据失败！', type: 'error' },
    300: { msg: '操作成功！', type: 'success' },
    301: { msg: '操作失败！', type: 'error' },
}

App({
    onLaunch() {
        // this.getDictData()
    },
    async getDictData() {
        const { data } = await this.requestAll({
            url: 'dict/selectList',
            alert: false
        })
        const list = arrayToMap(data)
        console.log(list);
    },
    requestAll({ url, params, method, header, alert = true }) {
        wx.showLoading({
            title: "加载中...",
            mask: true,
        });
        return new Promise(async (resolve, reject) => {
            const res = await wx.p.request({
                url: baseUrl + url,
                method: method,
                data: params,
                dataType: 'json',
                // header: header || { 'content-type': 'application/json' },
                header: header || { "content-type": "application/x-www-form-urlencoded", "token": wx.getStorageSync('bk-token') }
            })
            if (res.errMsg === 'request:ok') {
                const code = res.data.code
                if(code === 402){
                    wx.removeStorageSync('bk-token')
                    wx.removeStorageSync('userInfo')
                }
                setTimeout(() => {
                    wx.hideLoading()
                    if (code !== 200 && alert) {
                        wx.showToast({
                            title: MsgType[code].msg,
                            icon: MsgType[code].type
                        })
                    }
                }, 200)
                resolve(res.data)
            } else {
                setTimeout(() => {
                    wx.hideLoading()
                    wx.showToast({
                        title: '网络请求失败',
                        icon: 'error'
                    })
                }, 200)
                reject(null)
            }
        })
    },
    globalData: {
        userInfo: null,
        baseUrl,
        viewUrl,
    }
})
